﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using BryhtCommon;
using BryhtShare;
using BryhtControls;
using System.IO;
using System.Collections.ObjectModel;
using System.Windows.Controls.Primitives;
using System.Diagnostics;
using System.Threading;
namespace MyRun.Views
{
    public partial class Message : PhoneApplicationPage
    {
        public Message()
        {
            InitializeComponent();
        }
        private string liverUserName = string.Empty;
        private int _firstMessageId = int.MaxValue;
        private int _lastMessageId = 0;
        private Button btnBeforeMessages = null;
        private bool _isLoadingAddMessages = false;
        private ObservableCollection<MessageModel> _messageSource = new ObservableCollection<MessageModel>();

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            _messageSource.Clear();
            if (Isolated.Get("LiveUserName") != null && Isolated.Get("LiveUserName").ToString() != string.Empty)
            {
                liverUserName = Isolated.Get("LiveUserName").ToString();
                //加载留言
                LoadMessages();
            }
            else//获取UserID
            {
                ShareTool share = new ShareTool(this);
                share.LoginSuccessfulEvect += () =>
                {
                    ShareSkydrive skyShare = new ShareSkydrive();
                    skyShare.GetUserInfo((successful, userId, userName) =>
                    {
                        if (successful)
                        {
                            liverUserName = userName;
                            Isolated.Set("LiveUserId", userId);
                            Isolated.Set("LiveUserName", userName);
                            //加载留言
                            LoadMessages();
                        }
                        else
                        {
                            ThrowMessage.Show(MessageType.Error, userId);
                        }

                    });
                };
                share.LoginSkydrive();
            }
        }

        private void LoadMessages()
        {
            var request = new SimpleHttpRequest("http://www.bryht.net/MessageHandler.ashx");
            request.AddPara("queryType", "searchTop");
            request.AddPara("topCount", "20");
            request.AddPara("token", Guid.NewGuid());
            request.Get((ok, result) =>
            {

                if (ok)
                {
                    var messages = result.Split('&');
                    for (int i = 1; i < messages.Length; i++)
                    {
                        var m = messages[messages.Length - i - 1];
                        var id = int.Parse(HttpUtility.UrlDecode(m.Split('=')[0]));
                        var u = HttpUtility.UrlDecode(m.Split('=')[1]);
                        var c = HttpUtility.UrlDecode(m.Split('=')[2]);
                        var message = new MessageModel();
                        message.UserName = u;
                        message.Message = c;
                        _messageSource.Add(message);
                        _lastMessageId = id > _lastMessageId ? id : _lastMessageId;
                        _firstMessageId = id < _firstMessageId ? id : _firstMessageId;
                    }
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        lstMessage.ItemsSource = _messageSource;
                        lstMessage.UpdateLayout();
                        lstMessage.ScrollIntoView(lstMessage.Items.Last());
                    });
                }
                else
                {
                    ThrowMessage.Show(MessageType.Error, result);
                }

            });
        }

        private void LoadAddedMessages()
        {
            _isLoadingAddMessages = true;
            var request = new SimpleHttpRequest("http://www.bryht.net/MessageHandler.ashx");
            request.AddPara("queryType", "search");
            request.AddPara("messageCount", "20");
            request.AddPara("maxid", _lastMessageId);
            request.AddPara("token", Guid.NewGuid());
            request.Get((ok, result) =>
            {
                if (ok)
                {
                    var messages = result.Split('&');
                    for (int i = 0; i < messages.Length - 1; i++)
                    {
                        var m = messages[i];
                        var id = int.Parse(HttpUtility.UrlDecode(m.Split('=')[0]));
                        var u = HttpUtility.UrlDecode(m.Split('=')[1]);
                        var c = HttpUtility.UrlDecode(m.Split('=')[2]);
                        var message = new MessageModel();
                        message.UserName = u;
                        message.Message = c;
                        this.Dispatcher.BeginInvoke(() =>
                     {
                         _messageSource.Add(message);
                         lstMessage.UpdateLayout();
                         lstMessage.ScrollIntoView(message);
                     });
                        _lastMessageId = id > _lastMessageId ? id : _lastMessageId;
                    }

                }
                else
                {
                    ThrowMessage.Show(MessageType.Error, result);
                }

                _isLoadingAddMessages = false;
            });
        }

        private void LoadBeforeMessages()
        {
            var request = new SimpleHttpRequest("http://www.bryht.net/MessageHandler.ashx");
            request.AddPara("queryType", "searchBefore");
            request.AddPara("messageCount", "8");
            request.AddPara("maxid", _firstMessageId);
            request.AddPara("token", new DateTime().Millisecond);
            request.Get((ok, result) =>
            {
                if (ok)
                {
                    var messages = result.Split('&');
                    var flagMessage = _messageSource.First();
                    for (int i = 0; i < messages.Length - 1; i++)
                    {
                        var m = messages[i];
                        var id = int.Parse(HttpUtility.UrlDecode(m.Split('=')[0]));
                        var u = HttpUtility.UrlDecode(m.Split('=')[1]);
                        var c = HttpUtility.UrlDecode(m.Split('=')[2]);
                        var message = new MessageModel();
                        message.UserName = u;
                        message.Message = c;
                        Thread.Sleep(50);//显示逐渐添加的感觉
                        this.Dispatcher.BeginInvoke(() =>
                        {
                            _messageSource.Insert(0, message);
                            lstMessage.UpdateLayout();
                            lstMessage.ScrollIntoView(message);
                        });
                        _firstMessageId = id < _firstMessageId ? id : _firstMessageId;
                    }

                }
                else
                {
                    ThrowMessage.Show(MessageType.Error, result);
                }
                DisplayButton();
            });

        }

        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            var message = txtMessage.Text;
            if (message == string.Empty)
            {
                return;
            }
            var request = new SimpleHttpRequest("http://www.bryht.net/MessageHandler.ashx");
            request.AddPara("queryType", "add");
            request.Post((stream) =>
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.WriteLine("content=" + HttpUtility.UrlEncode(message) + "&username=" + HttpUtility.UrlEncode(liverUserName));
                }

            }, (ok, result) =>
            {

                if (ok)
                {
                    if (result.Split('=')[0] == "ok")
                    {

                        this.Dispatcher.BeginInvoke(() =>
                        {
                            LoadAddedMessages();
                            txtMessage.Text = string.Empty;
                            _lastMessageId = int.Parse(result.Split('=')[1]);
                        });
                    }
                }
                else
                {
                    ThrowMessage.Show(MessageType.Error, result);
                }
            });




        }

        private void ScrollViewer_MouseMove(object sender, MouseEventArgs e)
        {
            ScrollViewer o = sender as ScrollViewer;
            //Debug.WriteLine(o.VerticalOffset + "/" + o.ScrollableHeight);
            if (o.VerticalOffset == 0)
            {
                var panel = o.Content as StackPanel;
                btnBeforeMessages = panel.FindName("btnBeforeMessages") as Button;
                if (btnBeforeMessages.Visibility == Visibility.Collapsed)
                {
                    btnBeforeMessages.Visibility = Visibility.Visible;
                }
            }
            else if (o.VerticalOffset == o.ScrollableHeight && _isLoadingAddMessages == false)
            {
                LoadAddedMessages();
            }
        }

        private void btnBeforeMessages_Click(object sender, RoutedEventArgs e)
        {
            LoadBeforeMessages();
        }

        private void DisplayButton()
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                if (btnBeforeMessages != null && btnBeforeMessages.Visibility == Visibility.Visible)
                {
                    btnBeforeMessages.Visibility = Visibility.Collapsed;
                }
            });
        }


    }

    public class MessageModel
    {
        private string _message = string.Empty;

        public string Message
        {
            get { return _message; }
            set { _message = value; }
        }
        private string _userName = string.Empty;

        public string UserName
        {
            get { return _userName; }
            set { _userName = value; }
        }
    }
}